//
//  LoginViewController.m
//  EnglishTalk
//
//  Created by DING FENG on 6/27/14.
//  Copyright (c) 2014 ishowtalk. All rights reserved.
//

#import "FZLoginViewController.h"
//#import "LoginView.h"
//#import "LoginItem.h"
#import <ThirdPartyLoginAndShareSDK/WXApi.h>
#import "WeiboSDK.h"
#import "WBHttpRequest+WeiboUser.h"
#import <CommonCrypto/CommonDigest.h>
#import <UMMobClick/MobClick.h>
#import "FZRegisterViewController.h"
#import <Masonry.h>
#import "FCUtil.h"
#import "SRLoginManager.h"
#import "SRCommonHeader.h"
#import "UIButton+FZGreenButton.h"
#import <OpenUDID.h>
#import "FZDirectionButton.h"
#import <ESFrameworkUIKit/ESFrameworkUIKit.h>

static NSString *const kThirdLoginNotSupportedTip = @"你的手机暂不支持该登录方式";

@interface FZLoginViewController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView *inputBgView;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIView *textSeparatorView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textSeparatorHeightConstraint;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UIButton *forgotPasswordButton;
@property (weak, nonatomic) IBOutlet UIView *loginBottomLineView;

//@property (strong, nonatomic) UIView *thirdLoginBackgroundView;//灰色背景视图
@property (weak, nonatomic) IBOutlet UIView *thirdLoginView;
@property (strong, nonatomic) UIView *thirdCancelLineView;
//@property (weak, nonatomic) IBOutlet UIView *lineRightView;
//@property (weak, nonatomic) IBOutlet UILabel *thirdLoginTipLabel;

@property (weak, nonatomic) IBOutlet UIButton *thirdLoginEntranceButton;
@property (strong, nonatomic) FZDirectionButton *qqLoginButton;
@property (strong, nonatomic) FZDirectionButton *weiboLoginButton;
@property (strong, nonatomic) FZDirectionButton *weChatLoginButton;
@property (strong, nonatomic) UIButton *cancelThirdLoginButton;

@property (strong, nonatomic) UIButton *cancelButton;
@property (assign, nonatomic) BOOL didShowLoginTip;//已经显示登录提示；

@property (strong, nonatomic) NSMutableArray *visiableLoginButtons;//显示的登录按钮
@property (weak, nonatomic) IBOutlet UIView *lastLoginView;
@property (weak, nonatomic) IBOutlet UILabel *lastLoginTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *lastLoginLabel;

@end

@implementation FZLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.showCancelButton = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"登录";
    
//    [self setupNavigationView];
    [self setupView];
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];

    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [cancelButton setTitleColor:css.colorOfGreenButtonNormal forState:UIControlStateNormal];
    [cancelButton setTitleColor:css.colorOfGreenButtonHightlighted forState:UIControlStateHighlighted];
    [cancelButton setTitle:@"取消"  forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(onCancelButton:) forControlEvents:UIControlEventTouchUpInside];
    
    cancelButton.frame = CGRectMake(0, 0, 60, 44);
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
    [self setLeftBarButtonItem:leftBarItem];
    self.cancelButton = cancelButton;
    self.cancelButton.hidden = !self.showCancelButton;
    
    if (self.loginTip) {
        self.didShowLoginTip = NO;
    } else {
        self.didShowLoginTip = YES;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActiveNotification:) name:UIApplicationDidBecomeActiveNotification object:nil];
    /**
     *  添加返回按钮
     */
    [self setLeftBarButtonItemWithGray];
}

-(void)doBack {
    if (self.loginCancelBlock) {
        self.loginCancelBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSString *lastMobile = [SRLoginUser phone];
    if (lastMobile) {
        self.phoneTextField.text = lastMobile;
    }
    [self layoutThirdLoginView];
    
    
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    NSString *lastLogin = [userDefaults valueForKey:kLastLoginUserDefaultsKey];
//    if (lastLogin && ![lastLogin isEqualToString:@""]) {
//        self.lastLoginView.hidden = NO;
//        self.lastLoginLabel.text = lastLogin;
//    } else {
//        self.lastLoginView.hidden = YES;
//    }
    
    [self setClearNavigationBar:NO];
//    self.navigationController.navigationBar.titleTextAttributes = nil;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self.navigationController setNavigationBarHidden:NO];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (!self.didShowLoginTip && self.loginTip) {
        [self showHUDHintWithText:self.loginTip];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}


- (void)setupView {
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    self.view.backgroundColor = css.color_2;
    self.inputBgView.backgroundColor = css.color_2;
    [[UITextField appearance] setTintColor:css.color_1];
    self.phoneTextField.delegate = self;
    self.passwordTextField.delegate = self;
    
    self.textSeparatorHeightConstraint.constant = 0.5f;
    self.textSeparatorView.backgroundColor = self.loginBottomLineView.backgroundColor = css.colorOfSeperatorOnLightBackground;
    
    [self.loginButton applyEllipseGreenBackgroundColor];
    
    self.forgotPasswordButton.titleLabel.font = css.fontOfH6;
    [self.forgotPasswordButton setTitleColor:css.color_4 forState:UIControlStateNormal];
    
    [self.registerButton setTitleColor:css.color_4 forState:UIControlStateNormal];
    self.registerButton.titleLabel.font = css.fontOfH6;

    self.thirdLoginEntranceButton.titleLabel.font = css.fontOfH6;
    [self.thirdLoginEntranceButton setTitleColor:css.color_4 forState:UIControlStateNormal];
    
    [self.loginButton addTarget:self action:@selector(onLoginButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.registerButton addTarget:self action:@selector(onRegisterButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.forgotPasswordButton addTarget:self action:@selector(onForgotPasswordButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.thirdLoginEntranceButton addTarget:self action:@selector(onThirdLoginEntranceButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self setupThirdLoginView];
    
    self.lastLoginTitleLabel.font = css.fontOfH3;
    self.lastLoginTitleLabel.textColor = css.color_4;
    
    self.lastLoginLabel.font = css.fontOfH2;
    self.lastLoginLabel.textColor = css.color_4;
    
    self.lastLoginView.hidden = YES;
}

- (void)setupNavigationView {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 60, 44);
    rightButton.titleLabel.font = css.fontOfH2;
    [rightButton setTitle:@"注册" forState:UIControlStateNormal];
    
    [rightButton setTitleColor:css.colorOfGreenButtonNormal forState:UIControlStateNormal];
    [rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [rightButton addTarget:self action:@selector(onRegisterButton:) forControlEvents:UIControlEventTouchUpInside];
    self.registerButton = rightButton;
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    [self setRightBarButtonItem:rightBarItem];
}

- (void)setupThirdLoginView {
    
    self.visiableLoginButtons = [@[] mutableCopy];
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
//    self.thirdLoginBackgroundView = [[UIView alloc] init];
//    self.thirdLoginBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
//    [self.view addSubview:self.thirdLoginBackgroundView];
//    self.thirdLoginBackgroundView.hidden = NO;
//    
//    [self.thirdLoginBackgroundView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.leading.trailing.top.bottom.equalTo(self.view);
//    }];
    
    
//    WEAKSELF
//    [self.thirdLoginBackgroundView addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
//        [weakSelf onCancelThirdLoginButton:nil];
//    }];
    
//    self.thirdLoginView = [[UIView alloc] init];
    self.thirdLoginView.backgroundColor = css.color_1;
//    [self.thirdLoginBackgroundView addSubview:self.thirdLoginView];
    
    self.thirdCancelLineView = [[UIView alloc] init];
    self.thirdCancelLineView.backgroundColor = css.colorOfSeperatorOnLightBackground;
    [self.thirdLoginView addSubview:self.thirdCancelLineView];

    
    self.weiboLoginButton = [self buttonWithIconImage:[UIImage imageNamed:@"share_icon_weico"] title:@"微博"];
    self.qqLoginButton = [self buttonWithIconImage:[UIImage imageNamed:@"share_icon_QQ"] title:@"QQ"];
    self.weChatLoginButton = [self buttonWithIconImage:[UIImage imageNamed:@"share_icon_weixin"] title:@"微信"];
    
    [self.weiboLoginButton addTarget:self action:@selector(onSinaWeiboLoginButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.qqLoginButton addTarget:self action:@selector(onQQLoginButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.weChatLoginButton addTarget:self action:@selector(onWeChatLoginButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.thirdLoginView addSubview:self.weiboLoginButton];
    [self.thirdLoginView addSubview:self.weChatLoginButton];
    [self.thirdLoginView addSubview:self.qqLoginButton];
    
//    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    cancelButton.titleLabel.font = css.fontOfH2;
//    [cancelButton setTitleColor:css.color_4 forState:UIControlStateNormal];
//    [cancelButton setTitle:@"cancel"  forState:UIControlStateNormal];
//    [cancelButton addTarget:self action:@selector(onCancelThirdLoginButton:) forControlEvents:UIControlEventTouchUpInside];
//    self.cancelThirdLoginButton = cancelButton;
//    [self.thirdLoginView addSubview:self.cancelThirdLoginButton];
    
    [self.view addSubview:self.thirdLoginView];
    [self layoutThirdLoginView];
}

- (void)layoutThirdLoginView {
    CGFloat iconWidth = 40;
    CGFloat iconHeight = 60;
//    [self.visiableLoginButtons removeAllObjects];
    
//    [self.visiableLoginButtons addObject:self.weiboLoginButton];
    BOOL wechatInstalled = [WXApi isWXAppInstalled];
    if (wechatInstalled) {
        self.weChatLoginButton.hidden = NO;
//        [self.visiableLoginButtons addObject:self.weChatLoginButton];
    } else {
        self.weChatLoginButton.hidden = YES;
    }
    self.qqLoginButton.hidden = NO;
//    [self.thirdLoginView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.leading.trailing.bottom.equalTo(self.view);
//        make.height.mas_equalTo(100);
//    }];
    
    
//    [self.cancelThirdLoginButton mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.leading.trailing.bottom.equalTo(self.thirdLoginView);
//        make.height.mas_equalTo(44);
//    }];
//    
//    [self.thirdCancelLineView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.leading.trailing.equalTo(self.thirdLoginView);
//        make.bottom.equalTo(self.cancelThirdLoginButton.mas_top);
//        make.height.mas_equalTo(0.5);
//    }];
    
    if (wechatInstalled) {
            //显示微信
        NSInteger itemCount = 3;
        CGFloat edgeSpace = 25;
        CGFloat itemSpace = (SCREEN_WIDTH -  iconWidth * itemCount - edgeSpace * 2) / itemCount;
        [self.qqLoginButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.thirdLoginView).offset(edgeSpace + itemSpace/2.0);
            make.top.equalTo(self.thirdLoginView).offset(60);
            make.width.mas_equalTo(iconWidth);
            make.height.mas_equalTo(iconHeight);
        }];
        
        [self.weChatLoginButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.qqLoginButton.mas_trailing).offset(itemSpace);
            make.top.equalTo(self.qqLoginButton.mas_top);
            make.width.mas_equalTo(iconWidth);
            make.height.mas_equalTo(iconHeight);
        }];
        
        [self.weiboLoginButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(self.thirdLoginView).offset(- edgeSpace - itemSpace/2.0);
            make.top.equalTo(self.qqLoginButton.mas_top);
            make.width.mas_equalTo(iconWidth);
            make.height.mas_equalTo(iconHeight);
        }];
        
        
    } else {
            //不显示微信
        NSInteger itemCount = 2;
        CGFloat edgeSpace = 25;
        CGFloat itemSpace = (SCREEN_WIDTH -  iconWidth * itemCount - edgeSpace * 2) / itemCount;
        [self.qqLoginButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.thirdLoginView).offset(edgeSpace + itemSpace/2.0);
            make.top.equalTo(self.thirdLoginView).offset(60);
            make.width.mas_equalTo(iconWidth);
            make.height.mas_equalTo(iconHeight);
        }];
        
        [self.weiboLoginButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(self.thirdLoginView).offset(- edgeSpace - itemSpace/2.0);
            make.top.equalTo(self.qqLoginButton.mas_top);
            make.width.mas_equalTo(iconWidth);
            make.height.mas_equalTo(iconHeight);
        }];
    }
    
    
}

- (FZDirectionButton *)buttonWithIconImage:(UIImage *)iconImage title:(NSString *)title {
    CGFloat iconWidth = 40;
    FZDirectionButton *button = [FZDirectionButton buttonWithType:UIButtonTypeCustom];
    button.layoutDirection = FZDirectionButtonLayoutVerticalImageUp;
    button.betweenSpace = 10;
    
    button.frame = CGRectMake(0, 0, iconWidth, iconWidth + 20);
    [button setImage:iconImage forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = [FZStyleSheet currentStyleSheet].fontOfH7;
    [button setTitleColor:[FZStyleSheet currentStyleSheet].color_4 forState:UIControlStateNormal];
    
    return button;
}

#pragma mark - Event

-(void)onLoginButton:(UIButton *)sender{
    
    [self.view endEditing:YES];
    if (self.phoneTextField.text.length < 1 ){
        [self showHUDHintWithText:@"请填写你的手机号码"];
        return;
    }
    
    if (self.passwordTextField.text.length < 1) {
        [self showHUDHintWithText:@"请输入密码"];
        return;
    }
    
    [SRLoginUser setuserLoginAcount:self.phoneTextField.text];
    [SRLoginUser setuserLoginPassword:self.passwordTextField.text];
    
    [self startProgressHUDWithText:@"正在登录..."];
    NSString *mobile = self.phoneTextField.text;
    NSString *password = self.passwordTextField.text;
    NSString *devicetoken = [self uniqID];
    NSMutableDictionary *parameters = [@{} mutableCopy];
    [parameters setValue:mobile forKey:@"mobile"];
    [parameters setValue:password forKey:@"password"];
//    [parameters setValue:[FCUtil md5HexString:password] forKey:@"password"];

    [parameters setValue:devicetoken forKey:@"devicetoken"];
    
    WEAKSELF
    NSString *url = [[SRAPICreater sharedInstance] APIWithName:@"user_login"];
    
    [[SRNetWorkManager sharedInstance] POSTNODefaultParamWithUrl:url parameters:parameters responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess && dataObject) {
            [[SRLoginManager sharedManager] updateUserInfo:dataObject];
            [SRLoginUser setPhone:mobile];
            [self exitWithSuccess];
        } else {
            [weakSelf exitWithFailure:message];
        }
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDErrorMessage:@"登录失败，请检查网络"];
        [weakSelf exitWithFailure:nil];
    }];
    
}


- (IBAction)onRegisterButton:(UIButton *)sender {
    FZRegisterViewController *viewController = [[FZRegisterViewController alloc] initWithNibName:@"FZRegisterViewController" bundle:nil];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)onForgotPasswordButton:(UIButton *)sender {
    
    //忘记密码点击 add by zhouyongyang
    [MobClick event:@"Forget_password"];
    
    FZRegisterViewController *viewController = [[FZRegisterViewController alloc] initWithNibName:@"FZRegisterViewController" bundle:nil];
    viewController.isResetPassword = YES;
    [self.navigationController pushViewController:viewController animated:YES];
}

/**
 *  qq登录
 */
- (void)onQQLoginButton:(UIButton *)sender {
    [MobClick event:@"QQ_sign_in"]; //add by zhouyongyang
    
//    self.thirdLoginBackgroundView.hidden = YES;
    [[SRLoginManager sharedManager] onQQLogin];
}
/**
 *  新浪登录
 */
- (void)onSinaWeiboLoginButton:(UIButton *)sender {
//    self.thirdLoginBackgroundView.hidden = YES;
    [MobClick event:@"weibo_Sign_in"]; //add by zhouyongyang
    WBAuthorizeRequest * request = [WBAuthorizeRequest request];
    request.shouldOpenWeiboAppInstallPageIfNotInstalled = YES;
    request.shouldShowWebViewForAuthIfCannotSSO = YES;
    request.redirectURI = kSinaAPPURL;
    request.scope = @"all";
    
    [WeiboSDK sendRequest:request];
}
/**
 *  微信登录
 */
- (void)onWeChatLoginButton:(UIButton *)sender {
//    self.thirdLoginBackgroundView.hidden = YES;
    [MobClick event:@"WeChat_sign_in"]; //add by zhouyongyang
    BOOL weChatInstalled = [WXApi isWXAppInstalled];
    if (weChatInstalled) {
        //构造SendAuthReq结构体
        SendAuthReq* request = [[SendAuthReq alloc] init];
        request.scope = @"snsapi_userinfo";
        request.state = @"EnglishDubbging";
        
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:request];
    } else {
        [self showHUDHintWithText:kThirdLoginNotSupportedTip];
    }
}


- (void)setShowCancelButton:(BOOL)showCancelButton {
    _showCancelButton = showCancelButton;
    self.cancelButton.hidden = !showCancelButton;
}

- (void)onCancelButton:(UIButton *)sender {
//    WEAKSELF
//    [self dismissViewControllerAnimated:YES completion:^{
        if (self.loginCancelBlock) {
            self.loginCancelBlock();
        }
    [self.navigationController popViewControllerAnimated:YES];
//    }];
}

- (void)onThirdLoginEntranceButton:(UIButton *)sender {
//    if (self.thirdLoginView.hidden) {
//        self.thirdLoginBackgroundView.hidden = NO;
//    }
//    else {
//        self.thirdLoginView.hidden = YES;
//    }
//    self.thirdLoginBackgroundView.alpha = 0;
//
//    [UIView animateWithDuration:0.3 animations:^{
//        self.thirdLoginBackgroundView.alpha = 1;
//    } completion:^(BOOL finished) {
////        self.thirdLoginBackgroundView.hidden = YES;
////        self.thirdLoginBackgroundView.alpha = 1;
//    }];
    
}

//- (void)onCancelThirdLoginButton:(id)sender {
//    [UIView animateWithDuration:0.3 animations:^{
//        self.thirdLoginBackgroundView.alpha = 0;
//    } completion:^(BOOL finished) {
//        self.thirdLoginBackgroundView.hidden = YES;
//        self.thirdLoginBackgroundView.alpha = 1;
//    }];
//}

- (void)exitWithSuccess {
    WEAKSELF
//    [self dismissViewControllerAnimated:YES completion:^{
//        if (weakSelf.loginSuccessBlock) {
//            weakSelf.loginSuccessBlock();
//        }
//    }];
    
    [[SRLoginManager sharedManager] saveLoginSuccessType:@"手机登录"];
    
    if (weakSelf.loginSuccessBlock) {
        weakSelf.loginSuccessBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)exitWithFailure:(NSString *)errorMessage {
    WEAKSELF
//    [self dismissViewControllerAnimated:YES completion:^{
        if (weakSelf.loginFailureBlock) {
            weakSelf.loginFailureBlock(errorMessage);
        }
//    }];
//        [self.navigationController popViewControllerAnimated:YES];
}

- (void)appDidBecomeActiveNotification:(NSNotification *)notification {
    [self layoutThirdLoginView];
}

#pragma mark -获取UUID

- (NSString*)uniqID {
    NSString* uniqueIdentifier = kUniqueIdentifier;
    return uniqueIdentifier;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if (textField == self.passwordTextField) {
        [self onLoginButton:self.loginButton];
    }
    return YES;
}


@end
